<template>
<el-container>
    <el-header>
      <TopBar />
  </el-header>
  <el-main class="el-main">
    <div class="content">
      <div class="publish-container">
        <div class="publish-box">
          <div class="decoration-circle circle-1"></div>
          <div class="decoration-circle circle-2"></div>
          <div class="decoration-line line-1"></div>
          <div class="decoration-line line-2"></div>

          <h2>分享新动态</h2>
          <div class="subtitle">与大家分享你的精彩时刻</div>

          <div class="input-group">
            <div class="input-wrapper">
              <div class="input-label">标题</div>
              <input
                v-model="title"
                class="custom-input"
                placeholder="为你的动态写个标题吧..."
              />
            </div>
            <div class="input-wrapper">
              <div class="input-label">内容</div>
              <textarea
                v-model="description"
                rows="10"
                resize="none"
                class="custom-textarea"
                placeholder="写下你想分享的内容..."
              ></textarea>
            </div>

            <div class="media-section">
              <div class="section-title">
                <i class="el-icon-picture-outline"></i>
                <span>添加图片</span>
              </div>
              <div class="upload-area" @click="triggerFileInput">
                <input
                  ref="fileInput"
                  type="file"
                  @change="onFileChange"
                  accept="image/*"
                  class="file-input"
                />
                <div v-if="!selectedFile" class="upload-placeholder">
                  <i class="el-icon-upload"></i>
                  <div>点击上传图片</div>
                  <div class="upload-tip">支持 jpg、png、gif 格式</div>
                </div>
                <div v-else class="file-preview">
                  <div class="file-info">
                    <i class="el-icon-document"></i>
                    <span class="file-name">{{ selectedFile.name }}</span>
                  </div>
                  <button class="remove-file" @click.stop="removeFile">
                    <i class="el-icon-delete"></i>
                  </button>
                </div>
              </div>
            </div>

            <!-- 发布范围选择 -->
            <div class="scope-section">
              <div class="section-title">
                <i class="el-icon-share"></i>
                <span>发布范围</span>
              </div>
              <div class="scope-options">
                <!-- 首页选项 -->
                <div class="scope-option">
                  <input
                    type="checkbox"
                    id="scope-homepage"
                    v-model="publishScope.homepage"
                    class="custom-checkbox"
                  />
                  <label for="scope-homepage">首页动态</label>
                </div>

                <!-- 学校选项 -->
                <div class="scope-option" :class="{ disabled: !userSchool }">
                  <input
                    type="checkbox"
                    id="scope-school"
                    v-model="publishScope.school"
                    :disabled="!userSchool"
                    class="custom-checkbox"
                  />
                  <label for="scope-school">
                    {{ userSchool ? schoolName : '未加入学校' }}
                  </label>
                </div>

                <!-- 社团选项 -->
                <div class="scope-option club-options" v-if="userClubs.length > 0">
                  <div class="club-options-header">
                    <input
                      type="checkbox"
                      id="scope-clubs-all"
                      v-model="allClubsSelected"
                      @change="toggleAllClubs"
                      class="custom-checkbox"
                    />
                    <label for="scope-clubs-all">所有社团</label>
                  </div>
                  <div class="club-list">
                    <div
                      v-for="club in userClubs"
                      :key="club._id"
                      class="club-option"
                    >
                      <input
                        type="checkbox"
                        :id="`scope-club-${club._id}`"
                        v-model="publishScope.clubs"
                        :value="club._id"
                        class="custom-checkbox"
                        @change="updateAllClubsState"
                      />
                      <label :for="`scope-club-${club._id}`">{{ club.clubname }}</label>
                    </div>
                  </div>
                </div>
                <div class="scope-option disabled" v-else>
                  <input
                    type="checkbox"
                    id="scope-clubs-none"
                    disabled
                    class="custom-checkbox"
                  />
                  <label for="scope-clubs-none">未加入社团</label>
                </div>
              </div>
            </div>
          </div>

          <div class="action-group">
            <button class="cancel-btn" @click="$router.go(-1)">取消</button>
            <button @click="submitPost" class="confirm-btn">
              <i class="el-icon-upload2"></i>
              发布动态
            </button>
          </div>
        </div>
      </div>
    </div>
  </el-main>
  </el-container>
</template>

<script setup>
import NavBar from '../components/NavBar.vue'
import TopBar from '../components/TopBar.vue'
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const title = ref('');
const description = ref('');
const selectedFile = ref(null);
const fileInput = ref(null);
const router = useRouter();

// 用户信息
const userSchool = ref(null); // 用户所属学校ID
const schoolName = ref(''); // 用户所属学校名称
const userClubs = ref([]); // 用户加入的社团列表
const allClubsSelected = ref(false); // 是否选中了所有社团

// 发布范围
const publishScope = ref({
  homepage: true, // 默认发布到首页
  school: false,  // 是否发布到学校
  clubs: []       // 发布到哪些社团
});

// 获取用户信息
async function fetchUserInfo() {
  try {
    const token = localStorage.getItem('token');
    if (!token) return;

    // 获取用户信息
    const userResponse = await axios.get('http://localhost:5000/users/me', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    const user = userResponse.data;

    // 设置用户学校
    if (user.school) {
      userSchool.value = user.school;

      // 获取学校名称
      try {
        const schoolResponse = await axios.get(`http://localhost:5000/school/${user.school}`);
        schoolName.value = schoolResponse.data.name;
      } catch (error) {
        console.error('获取学校信息失败:', error);
      }
    }

    // 获取用户加入的社团
    if (user.clubs && user.clubs.length > 0) {
      try {
        // 这里需要修改后端API，添加获取用户社团的接口
        const clubsResponse = await axios.get('http://localhost:5000/users/me/clubs', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        userClubs.value = clubsResponse.data || [];
      } catch (error) {
        console.error('获取用户社团失败:', error);
        userClubs.value = [];
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
}

// 切换所有社团选择状态
function toggleAllClubs() {
  if (allClubsSelected.value) {
    // 选中所有社团
    publishScope.value.clubs = userClubs.value.map(club => club._id);
  } else {
    // 取消选中所有社团
    publishScope.value.clubs = [];
  }
}

// 更新"所有社团"复选框状态
function updateAllClubsState() {
  // 如果所有社团都被选中，则"所有社团"也应被选中
  allClubsSelected.value =
    userClubs.value.length > 0 &&
    publishScope.value.clubs.length === userClubs.value.length;
}

function triggerFileInput() {
  fileInput.value.click();
}

function removeFile(event) {
  selectedFile.value = null;
  fileInput.value.value = '';
}

function onFileChange(event) {
  selectedFile.value = event.target.files[0];
}

async function submitPost() {
  const token = localStorage.getItem('token');
  if (!token) {
    alert('请先登录！');
    router.push('/login');
    return;
  }

  if (!title.value || !description.value) {
    alert('标题和内容不能为空');
    return;
  }

  // 检查至少选择一个发布范围
  if (!publishScope.value.homepage &&
      !publishScope.value.school &&
      publishScope.value.clubs.length === 0) {
    alert('请至少选择一个发布范围');
    return;
  }

  const formData = new FormData();
  formData.append('title', title.value);
  formData.append('description', description.value);

  // 添加发布范围
  formData.append('publishToHomepage', publishScope.value.homepage);

  if (publishScope.value.school && userSchool.value) {
    formData.append('publishToSchool', userSchool.value);
  }

  if (publishScope.value.clubs.length > 0) {
    // 将社团ID数组转换为JSON字符串
    formData.append('publishToClubs', JSON.stringify(publishScope.value.clubs));
  }

  if (selectedFile.value) {
    formData.append('image', selectedFile.value);
  }

  try {
    const response = await axios.post('http://localhost:5000/posts', formData, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    console.log('帖子发布成功:', response.data);
    router.push('/self');
  } catch (error) {
    console.error('发布帖子失败:', error);
  }
}

// 在组件挂载时获取用户信息
onMounted(() => {
  const token = localStorage.getItem('token');
  if (!token) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  fetchUserInfo();
});
</script>

<style>
body {
  background-color: #1f1b24;
  margin: 0;
  padding: 0;
}
::-webkit-scrollbar{
  display: none;
}
</style>

<style scoped>
.content {
  position: absolute; /* 绝对定位 */
  top: 60px; /* 距离顶部的距离等于顶部区域的高度 */
  left: 10vw; /* 距离左侧的距离等于左侧区域的宽度 */
  right: 10vw; /* 距离右侧为0，撑满剩余空间 */
  bottom: 0; /* 距离底部为0，撑满剩余空间 */
  padding: 20px; /* 为内容添加内边距 */
}

.publish-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.publish-box {
  position: relative;
  width: 100%;
  padding: 2vh 40px;
  background: #28232e;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

/* 装饰元素 */
.decoration-circle {
  position: absolute;
  border-radius: 50%;
  opacity: 0.15;
}

.circle-1 {
  width: 200px;
  height: 200px;
  background: linear-gradient(45deg, #3f51b5, #2196f3);
  top: -100px;
  right: -100px;
}

.circle-2 {
  width: 150px;
  height: 150px;
  background: linear-gradient(45deg, #9c27b0, #e91e63);
  bottom: -75px;
  left: -75px;
}

.decoration-line {
  position: absolute;
  background: linear-gradient(45deg, #424242, #616161);
  opacity: 0.3;
}

.line-1 {
  width: 100px;
  height: 3px;
  transform: rotate(45deg);
  top: 20%;
  left: -20px;
}

.line-2 {
  width: 150px;
  height: 3px;
  transform: rotate(-45deg);
  bottom: 30%;
  right: -40px;
}

h2 {
  color: #ffffff;
  text-align: center;
  font-size: 32px;
  margin: 1vh;
  font-weight: 600;
}

.subtitle {
  text-align: center;
  color: #b0bec5;
  margin-bottom: 40px;
  font-size: 16px;
}

.input-group {
  margin-bottom: 30px;
}

.input-wrapper {
  position: relative;
  margin-bottom: 25px;
  width: 100%;
  max-width: 100%;
}

.input-label {
  color: #b0bec5;
  margin-bottom: 8px;
  font-size: 14px;
}

.custom-input, .custom-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #424242;
  border-radius: 8px;
  background: #333333;
  color: #ffffff;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.custom-input:focus, .custom-textarea:focus {
  border-color: #3f51b5;
  outline: none;
  box-shadow: 0 0 0 2px rgba(63, 81, 181, 0.2);
}

.custom-input::placeholder, .custom-textarea::placeholder {
  color: #757575;
}

.custom-textarea {
  resize: none;
  min-height: 200px;
}

.media-section {
  background: #333333;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.section-title {
  color: #b0bec5;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.upload-area {
  border: 2px dashed #424242;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3f51b5;
  background: rgba(63, 81, 181, 0.1);
}

.upload-placeholder {
  color: #b0bec5;
}

.upload-tip {
  color: #757575;
  font-size: 12px;
  margin-top: 8px;
}

.file-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: #424242;
  border-radius: 6px;
  color: #ffffff;
}

.file-info {
  display: flex;
  align-items: center;
  color: #2c3e50;
}

.file-info i {
  margin-right: 8px;
  color: #3498db;
}

.remove-file {
  background: none;
  border: none;
  color: #e74c3c;
  cursor: pointer;
  padding: 5px;
  transition: all 0.2s ease;
}

.remove-file:hover {
  transform: scale(1.1);
}

.action-group {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
  margin-top: 30px;
}

.cancel-btn {
  padding: 10px 24px;
  border: 1px solid #424242;
  border-radius: 8px;
  background: transparent;
  color: #b0bec5;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #424242;
  color: #ffffff;
}

.confirm-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(45deg, #3f51b5, #2196f3);
  color: #ffffff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
}

.file-input {
  display: none;
}

.scope-section {
  background: #333333;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.scope-options {
  margin-top: 16px;
}

.scope-option {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 10px 16px;
  background: #2b2b2b;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.scope-option:hover:not(.disabled) {
  background: #383838;
}

.scope-option.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #262626;
}

.custom-checkbox {
  appearance: none;
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  background-color: #222;
  border: 2px solid #444;
  border-radius: 4px;
  margin-right: 12px;
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;
}

.custom-checkbox:checked {
  background-color: #00aeff;
  border-color: #00aeff;
}

.custom-checkbox:checked::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.custom-checkbox:disabled {
  background-color: #333;
  border-color: #444;
  cursor: not-allowed;
}

label {
  color: #b0bec5;
  cursor: pointer;
}

.scope-option.disabled label {
  cursor: not-allowed;
}

.club-options {
  flex-direction: column;
  align-items: flex-start;
}

.club-options-header {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 8px;
}

.club-list {
  margin-left: 30px;
  width: 100%;
  max-height: 180px;
  overflow-y: auto;
  padding-right: 10px;
}

.club-option {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px 12px;
  background: #222;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.club-option:hover {
  background: #2a2a2a;
}

/* 滚动条样式 */
.club-list::-webkit-scrollbar {
  width: 6px;
  display: block;
}

.club-list::-webkit-scrollbar-track {
  background: #2b2b2b;
}

.club-list::-webkit-scrollbar-thumb {
  background-color: #444;
  border-radius: 6px;
}

.club-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>
